package phoeics.authoryserver.webservice.service.impl;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import phoeics.authoryserver.webservice.entity.OauthRole;
import phoeics.authoryserver.webservice.entity.OauthUser;
import phoeics.authoryserver.webservice.repository.OauthUserRepository;
import phoeics.authoryserver.webservice.security.Account;
@Service
public class AccountDetailsServiceImpl implements UserDetailsService {
	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(AccountDetailsServiceImpl.class);
	 @Autowired
	 OauthUserRepository oauthUserRepository;
	 //OauthRoleRepository oauthRoleRepository;
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		OauthUser oauthUser=oauthUserRepository.findByUsername(username);
		if(oauthUser==null){
			throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
		}
		 Collection<SimpleGrantedAuthority> collection = new HashSet<>();
		 List<OauthRole> oauthRoles=oauthUser.getOauthRoles();
		 for(OauthRole oauthRole:oauthRoles){
			 collection.add(new SimpleGrantedAuthority(oauthRole.getName()) );
		 }
		return new Account(oauthUser,collection);
		
	}
}